package com.itany.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2023-01-04 10:06
 * Description：网关拦截，实现统一的登陆权限校验
 */
// @Component
public class LoginGatewayFilter  implements GlobalFilter, Ordered {
    /**
     * 定义过滤器的内容
     * @param exchange 用于操作请求/响应的相关信息
     * @param chain 用于过滤器放行
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("LoginGatewayFilter.filter........................");

        /**
         * 获取token信息，判断是否登陆，对异步请求进行响应
         */
        // 获取请求中的参数
        // String token = exchange.getRequest().getQueryParams().getFirst("token");
        // 获取Cookie中的参数
        HttpCookie token = exchange.getRequest().getCookies().getFirst("token");
        if(token == null){
            Map<String,Object> map = new HashMap<>();
            map.put("status", -1);
            map.put("msg","请求失败，请先登陆授权！");
            byte[] bytes = JSON.toJSONString(map).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);

            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
            return exchange.getResponse().writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    /**
     * 定义过滤器的优先级：值越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
